#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#define TRUE 1
#define FALSE 0
#define BUFFER_SIZE 10000

int main(int argc, char **argv) {
        char found_db                   = FALSE;
        char *buffer                    = NULL;
        char *db                        = NULL;
        FILE *fd                        = NULL;

        if (argc != 3) {
            fprintf(stderr, "USAGE: getdb <file> <database>\n");
            exit(1);
        }

        if ((fd = fopen(argv[1], "r")) == NULL) {
            perror("Could not open file\n");
            exit(1);
        }
        
        buffer = (char*)malloc(BUFFER_SIZE);
        db = (char*)malloc(strlen(argv[2])*sizeof(char)+1);


        while (!found_db) {

            if ((fscanf(fd, "%1000s", buffer)) == EOF) {
                break;
            }

            if (!strncmp(buffer, "USE", 4)) {
                    if ((fscanf(fd, "%1000s", buffer)) == EOF) {
                        break;
                    }

                    fprintf(stderr, "DEBUG: %s\n", buffer);
                    strncpy(db, buffer+1, strlen(buffer)-2);
                    db[strlen(buffer)-3]='\0';

                    fprintf(stderr, "%s %s\n", db, argv[2]);
                    if (!strncmp(db, argv[2], BUFFER_SIZE)) {
                        found_db = TRUE;
                        while (getc(fd) != '\n');
                        fprintf(stderr, "Got match\n");
                        break;
                    }
                    
            } else {
                while (getc(fd) != '\n');
            }
        }
        if (found_db) {
            while(getc(fd) != '\n');
            while ((fgets(buffer, BUFFER_SIZE, fd) != NULL) && (strncmp(buffer, "USE ", 4) != 0)) {
                printf("%s", buffer);
            }
        }
        free(buffer);
        fclose(fd);
        return 0;
}

